/*
 * appender.h
 *
 *  Created on: 2008-11-11
 *      Author: fanliangliang
 */

#ifndef APPENDER_H_
#define APPENDER_H_

#include "config.h"
#include "logger.h"
#include "string_util.h"
#include "lexical_cast.h"
#include <map>
#include <fstream>
#include <stdint.h>

BEGIN_NAMESPACE_TOXIC

using std::map;
using std::ofstream;
using std::ios_base;

class LogAppender {
public:
	LogAppender() {}
	virtual ~LogAppender() {}
	virtual void doAppend(const LogEvent& e) = 0;
};


class ConsoleAppender : public LogAppender {
public:
	explicit ConsoleAppender(ostream& out);
	virtual ~ConsoleAppender();
	virtual void doAppend(const LogEvent& e);

private:
	ostream& _out;
};


class FileAppender : public LogAppender {
	typedef map<unsigned, FileAppender*> TidAppenderMap;
public:
	explicit FileAppender(const char* format,
		ios_base::openmode mode = ios_base::out | ios_base::trunc);
	virtual ~FileAppender();
	virtual void doAppend(const LogEvent& e);
	virtual void print(ostream& ostrm, const LogEvent& e);

private:
	void close();

private:
	string _filename;
	string _format;
	ios_base::openmode _mode;
	ofstream _out;
	bool _hasTid;
	TidAppenderMap _map;
};


class Socket;
class ByteStream;

class SocketAppender : public LogAppender {
public:
	SocketAppender(const string& protocol, const string& server, uint16_t port);
	virtual ~SocketAppender();
	virtual void doAppend(const LogEvent& e);

private:
	void destory();

private:
	Socket* _socket;
	string _server;
	uint16_t _port;
};


ByteStream& operator<<(ByteStream& out, const LogEvent& e);
ByteStream& operator>>(ByteStream& in, LogEvent& e);

END_NAMESPACE_TOXIC

#endif /* APPENDER_H_ */
